package com.yksj.healthtalk.ui.salon;

import org.universalimageloader.core.ImageLoader;

import android.graphics.drawable.LevelListDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.PopWindowUtil;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 
 * 按组添加特殊收费人群
 * @author origin
 *
 */
public class SalonSpecialPeoplsMenberAddByGroupActivity extends
		BaseFragmentActivity implements OnClickListener, OnItemClickListener{
	
	ListView mListView;
	CheckBox mAllBox;
	CheckboxListAdapter mAdapter;
	JSONObject mJsonObject;
	String PATIENT_GROUP_ID;//分组id
	String groudId;//组id
	
	String Special_Group_ID;// 按门票 组id
	String Service_Group_ID;// 按服务 组id
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.salon_special_peopl_add_by_group_layout);
		
		if(arg0 != null){
			groudId = arg0.getString("groudId");
			Special_Group_ID = arg0.getString("Special_Group_ID");
			Service_Group_ID = arg0.getString("Service_Group_ID");
			String json = arg0.getString("json");
			mJsonObject = JSON.parseObject(json);
		}else{
			groudId = getIntent().getStringExtra("groudId");
			Special_Group_ID = getIntent().getStringExtra("Special_Group_ID");
			Service_Group_ID = getIntent().getStringExtra("Service_Group_ID");
			String json = getIntent().getStringExtra("json");
			mJsonObject = JSON.parseObject(json);
		}
		
		PATIENT_GROUP_ID = mJsonObject.getString("PATIENT_GROUP_ID");
		if(PATIENT_GROUP_ID == null || "null".equalsIgnoreCase(PATIENT_GROUP_ID)){
			PATIENT_GROUP_ID = "";
		}
		
		initUI();
		
		onQueryData();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("json",mJsonObject.toJSONString());
		outState.putString("groudId", groudId);
		outState.putString("Special_Group_ID", Special_Group_ID);
		outState.putString("Service_Group_ID", Service_Group_ID);
	}
	
	
	private void initUI(){
		initTitle();
		setTitle("添加成员");
		setBackBtn("返回",this);
		setRightBtnYellowBg("确定",this);
		
		mAllBox = (CheckBox)findViewById(R.id.check_all);
		mAllBox.setVisibility(View.GONE);
		mAllBox.setOnClickListener(this);
		
		mListView = (ListView)findViewById(android.R.id.list);
		mListView.setAdapter(mAdapter = new CheckboxListAdapter(getLayoutInflater()));
		mListView.setOnItemClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.check_all://全选
			if(mAllBox.isChecked()){
				mAdapter.onSelectAll();
			}else{
				mAdapter.unSelectAll();
			}
			break;
		case R.id.title_right2:
			if(mAdapter.getChooseJSONArray().size()==0){
				ToastUtil.showToastPanl("未选择添加成员");
				return;
			}else{
				addMenberNote(v);
			}
			break;
					// 跳过
					case R.id.note_jump:
						// 之后按此执行
						if (mNoteCheck.isChecked()) {
							if (mNoteWindow.isShowing()) {
								mNoteWindow.dismiss();
							}
							onAddMenber();
							return;
						}
						++noteIndex;// 索引添加,显示下一个
						onUpdateNote();
						break;
					// 移动
					case R.id.note_move:
						// 执行移动,从非需要移动列表中删除
						mAdapter.mOtherArray.remove(noteIndex);
						// 之后按此执行
						if (mNoteCheck.isChecked()) {
							if (mNoteWindow.isShowing()) {
								mNoteWindow.dismiss();
							}
							int size = mAdapter.mOtherArray.size();
							JSONArray array = new JSONArray();
							for (int i = noteIndex; noteIndex < size; i++) {
								array.add(mAdapter.mOtherArray.get(i));
							}
							mAdapter.mOtherArray.removeAll(array);
							onAddMenber();
							return;
						} else {
							onUpdateNote();// 显示下一个
						}
						break;
					case R.id.note_cancel:
						if (mNoteWindow.isShowing()) {
							mNoteWindow.dismiss();
						}
						noteIndex = 0;
						break;
					}
		
		}
	
	/**
	 * 添加提示
	 */
	private void addMenberNote(View v) {
		if (mNoteWindow != null && mNoteWindow.isShowing()) {
			return;
		}
		// 当前要添加的成员不在其他分组的时候不需要提示移动分组,直接添加
		if (mAdapter.mOtherArray.size() == 0) {
			onAddMenber();
			return;
		} else {
			showAddNoteWindow(v);
		}
	}

	// 添加提示
	CheckBox mNoteCheck;// 之后所有按选择执行
	TextView mNoteTxt;
	PopupWindow mNoteWindow;
	String note;
	int noteIndex = 0;
	
	
	/**
	 * 显示添加提示框
	 */
	private void showAddNoteWindow(View view) {
		note = getString(R.string.note_menber_add);
		View view2 = getLayoutInflater().inflate(
				R.layout.window_grou_menber_add, null);
		view2.findViewById(R.id.note_cancel).setOnClickListener(this);
		mNoteCheck = (CheckBox) view2.findViewById(R.id.note_check);
		view2.findViewById(R.id.note_jump).setOnClickListener(this);
		view2.findViewById(R.id.note_move).setOnClickListener(this);
		mNoteTxt = (TextView) view2.findViewById(R.id.note_txt);
		mNoteWindow = new PopupWindow(view2, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		PopWindowUtil.setWindow(mNoteWindow);
		mNoteWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
		noteIndex = 0;
		onUpdateNote();
	}

	/**
	 * 更新提示
	 */
	private void onUpdateNote() {
		// 已经循环到最后一个
		if (mAdapter.mOtherArray.size() <= noteIndex) {
			mNoteWindow.dismiss();
			onAddMenber();
		} else {
			JSONObject jsonObject = mAdapter.mOtherArray
					.getJSONObject(noteIndex);
			/*String nickName = jsonObject.getString("CUSTOMER_NICKNAME");
			String account = jsonObject.getString("CUSTOMER_ACCOUNTS");
			if(nickName != null){
				account = nickName +"("+account+")";
			}*/
			String name = jsonObject.getString("display_name");
			mNoteTxt.setText(String.format(note, name));
		}
	}
	
	/**
	 * 添加特殊收费人群
	 */
	private void onAddMenber(){
		if(Special_Group_ID != null){//话题特殊人群
//			customerids 客户id数组 specialGroupId 话题特殊收费人群id patientGroupId 分组id customerId 我的id type=addSalonSpecialPriceGroupMember
			RequestParams params = new RequestParams();
			final JSONArray array = mAdapter.getChooseJSONArray();
			mAdapter.mChoosedArray.removeAll(mAdapter.mOtherArray);
			final int size = array.size();
			if(size == 0 )return;
			final JSONArray jsonArray = new JSONArray();
			for (int i = 0; i < size; i++) {
				String id = array.getJSONObject(i).getString("CUSTOMER_ID");
				String groupid = array.getJSONObject(i).getString("SPECIAL_GROUP_ID");
				if(groupid == null || Special_Group_ID != groupid){
					jsonArray.add(id);
				}
			}
			if(jsonArray.size() == 0){
				ToastUtil.showShort("不能重复添加");
				return;
			}
			params.put("customerId", SmartFoxClient.getLoginUserId());
			params.put("type", "addSalonSpecialPriceGroupMember");
			params.put("specialGroupId", Special_Group_ID);
			params.put("customerIds", jsonArray.toJSONString());
			HttpRestClient.doHttpSalonSpecialPriceGroupSet(params, new AddResponseHandler());
		}else{//服务特殊收费人群
			RequestParams params = new RequestParams();
			final JSONArray array = mAdapter.getChooseJSONArray();
			mAdapter.mChoosedArray.removeAll(mAdapter.mOtherArray);
			final int size = array.size();
			if(size == 0 )return;
			final JSONArray jsonArray = new JSONArray();
			for (int i = 0; i < size; i++) {
				String id = array.getJSONObject(i).getString("CUSTOMER_ID");
				String groupid = array.getJSONObject(i).getString("SPECIAL_GROUP_ID");
				if(groupid == null || Special_Group_ID != groupid){
					jsonArray.add(id);
				}
			}
			if(jsonArray.size() == 0){
				ToastUtil.showShort("不能重复添加");
				return;
			}
			params.put("PARAME",jsonArray.toJSONString());
			params.put("Type", "addSpecialPriceGroupMember");
			params.put("CUSTOMER_ID",SmartFoxClient.getLoginUserId());
			params.put("SPECIAL_GROUP_ID",Service_Group_ID);
			params.put("SERVICE_ITEM_ID", getIntent().getStringExtra("SERVICE_ITEM_ID"));
			HttpRestClient.doHttpServicesetservletrj320(params, new AddResponseHandler());
		}
	}
	
	/**
	 * 
	 */
	private void onQueryData(){
		//按门票添加
		if(Service_Group_ID == null){
			if("-1".equals(PATIENT_GROUP_ID)){//我关注的朋友
				RequestParams params = new RequestParams();
				params.put("customerId",SmartFoxClient.getLoginUserId());
				params.put("type", "findMyFocusFriends");
				params.put("groupId", groudId);
				HttpRestClient.doHttpSalonSpecialPriceGroupSet(params, new QueryResponseHandler());
			}else if("-2".equals(PATIENT_GROUP_ID)){//关注我的朋友
				RequestParams params = new RequestParams();
				params.put("customerId",SmartFoxClient.getLoginUserId());
				params.put("type", "findFocusMeFriends");
				params.put("groupId", groudId);
				HttpRestClient.doHttpSalonSpecialPriceGroupSet(params, new QueryResponseHandler());
			}else if("-3".equals(PATIENT_GROUP_ID)){//我关注的医生
				RequestParams params = new RequestParams();
				params.put("customerId",SmartFoxClient.getLoginUserId());
				params.put("type", "findMyFocusDoctor");
				params.put("groupId", groudId);
				HttpRestClient.doHttpSalonSpecialPriceGroupSet(params, new QueryResponseHandler());
			}else{//患者分组
				RequestParams params = new RequestParams();
				params.put("customerId",SmartFoxClient.getLoginUserId());
				params.put("type", "findPatientsByGroup");
				params.put("patientGroupId", PATIENT_GROUP_ID);
				params.put("groupId", groudId);
				HttpRestClient.doHttpSalonSpecialPriceGroupSet(params, new QueryResponseHandler());
			}
		//按服务添加	
		}else{
			RequestParams params = new RequestParams();
			if("-1".equals(PATIENT_GROUP_ID)){
				params.put("type", "0");
			}else if("-2".equals(PATIENT_GROUP_ID)){
				params.put("type", "1");
			}else if("-3".equals(PATIENT_GROUP_ID)){
				params.put("type", "2");
			}else{
				params.put("type", "3");
			}
			params.put("customerId",SmartFoxClient.getLoginUserId());
			params.put("patientGroupId", PATIENT_GROUP_ID);
			params.put("serviceItemId", getIntent().getStringExtra("SERVICE_ITEM_ID"));
			HttpRestClient.doHttpFindFriendsByGroup(params, new QueryResponseHandler());
		/*	FindFriendsByGroup
			customerId
			type  0-我关注的朋友 1-关注我的朋友 2-我关注的医生 3-分组的患者
			serviceItemId  医生服务项目id
			patientGroupId  患者分组id*/
		}
		
	}
	
	/**
	 * 添加特殊人群返回
	 * @author origin
	 */
	class AddResponseHandler extends JsonsfHttpResponseHandler{
		public AddResponseHandler() {
			super(SalonSpecialPeoplsMenberAddByGroupActivity.this);
		}
		@Override
		public void onSuccess(int statusCode, JSONObject response) {
			super.onSuccess(statusCode, response);
			if(response.containsKey("error_message")){
				ToastUtil.showShort(response.getString("error_message"));
			}else{
				ToastUtil.showShort("添加成功");
			}
		}
	}
	
	/**
	 * 查询特殊收费人群返回
	 * @author origin
	 *
	 */
	class QueryResponseHandler extends JsonsfHttpResponseHandler{
		public QueryResponseHandler() {
			super(SalonSpecialPeoplsMenberAddByGroupActivity.this);
		}
		@Override
		public void onSuccess(int statusCode, JSONArray response) {
			mAllBox.setVisibility(View.VISIBLE);
			mAdapter.onDataChange(response);
		}
	}

	private class CheckboxListAdapter extends BaseAdapter {
		public  final JSONArray mOtherArray = new JSONArray();//已经在其他分组当中的成员
		final JSONArray mChoosedArray = new JSONArray();
		public JSONArray mArray = new JSONArray();
		public ViewHolder viewHolder;
		LayoutInflater mInflater;
		private final ImageLoader mImageLoader;
		
		public CheckboxListAdapter(LayoutInflater inflater){
			this.mInflater = inflater;
			this.mImageLoader = ImageLoader.getInstance();
		}
		
		public void onDataChange(JSONArray jsonArray){
			mChoosedArray.clear();
			this.mArray = jsonArray;
			mOtherArray.clear();
			notifyDataSetChanged();
		}
		
		/**
		 * 全选
		 */
		private void onSelectAll(){
			mChoosedArray.clear();
			mChoosedArray.addAll(mArray);
			notifyDataSetChanged();
		}
		
		/**
		 * 
		 *取消全选
		 * 
		 */
		private void unSelectAll(){
			mChoosedArray.clear();
			notifyDataSetChanged();
		}
		
		public JSONArray getChooseJSONArray(){
			return mChoosedArray;
		}
		
		private void onChoose(Object obj,boolean isChoosed){
			if(isChoosed){
				if(!mChoosedArray.contains(obj)){
					mChoosedArray.add(obj);
				}
			}else{
				mChoosedArray.remove(obj);
			}
			mAllBox.setChecked((mChoosedArray.size() == mArray.size()));
		}
		
		@Override
		public int getCount() {
			return mArray.size();
		}
		
		@Override
		public boolean isEmpty() {
			return false;
		}

		@Override
		public JSONObject getItem(int position) {
			return mArray.getJSONObject(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			final JSONObject object = getItem(position);
			if(convertView == null){
				viewHolder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.commn_checkbox_list_item,null);
				viewHolder.headerImageV = (ImageView)convertView.findViewById(R.id.head_image);
				viewHolder.nameTextV = (TextView)convertView.findViewById(R.id.name);
				viewHolder.sexImageV = (ImageView)convertView.findViewById(R.id.head_sex);
				viewHolder.roleImageV = (ImageView)convertView.findViewById(R.id.levl);
				viewHolder.noteTextV = (TextView)convertView.findViewById(R.id.note);
				viewHolder.chooseBox = (CheckBox)convertView.findViewById(R.id.choose);
				convertView.setTag(viewHolder);
			}else{
				viewHolder = (ViewHolder)convertView.getTag();
			}
			int sexLevel = 0;
			if(object.containsKey("SEX_DRAWABLE")){
				sexLevel = object.getIntValue("SEX_DRAWABLE");
			}else{
				String sex = object.getString("CUSTOMER_SEX");
				sexLevel = CustomerInfoEntity.parseSex(sex);
				object.put("SEX_DRAWABLE", sexLevel);
			}
			final LevelListDrawable listDrawable = (LevelListDrawable)viewHolder.sexImageV.getDrawable();
			listDrawable.setLevel(sexLevel);
			String name = object.getString("PERSONAL_NARRATE");
			int roleId = object.getIntValue("ROLE_ID");
			boolean isShow = CustomerInfoEntity.isShowDoctorV(roleId);
			viewHolder.roleImageV.setVisibility(isShow?View.VISIBLE:View.GONE);
			
			String account = null;
			if(object.getString("display_name") == null){
				String 	nickName = object.getString("CUSTOMER_NICKNAME");
				account = object.getString("CUSTOMER_ACCOUNTS");
				if(nickName != null){
					account = nickName +"("+account+")";
				}
				object.put("display_name", account);
			}else{
				account=object.getString("display_name");
			}
			viewHolder.noteTextV.setText(name);
			viewHolder.nameTextV.setText(account);
			viewHolder.chooseBox.setChecked(mChoosedArray.contains(object));
			viewHolder.chooseBox.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					CheckBox box  = (CheckBox)v;
					if(box.isChecked()){
						String Patient_Group_ID = object.getString("SPECIAL_GROUP_ID");//判断有没有在其他分组中
						if(Patient_Group_ID != null && Patient_Group_ID.length() != 0 && 
								!Patient_Group_ID.equals(Special_Group_ID == null ? Service_Group_ID:Special_Group_ID )){
							mOtherArray.add(object);
						}
						mChoosedArray.add(object);
					}else{
						mChoosedArray.remove(object);
						mOtherArray.remove(object);
					}
				}
			});
			mImageLoader.displayImage(String.valueOf(sexLevel),object.getString("CLIENT_ICON_BACKGROUND"),viewHolder.headerImageV);
			return convertView;
		}
		
		/**
		 * 
		 * @param position
		 */
		public void isChoose(int position){
			JSONObject jsonObject = mAdapter.getItem(position);
			String Patient_Group_ID = jsonObject.getString("SPECIAL_GROUP_ID");//判断有没有在其他分组中
			if(mChoosedArray.contains(jsonObject)){//说明已经添加 移除
				mChoosedArray.remove(jsonObject);
				mOtherArray.remove(jsonObject);
			}else{//需要添加
				if(Patient_Group_ID != null && Patient_Group_ID.length() != 0 && 
						!Patient_Group_ID.equals(Special_Group_ID == null ? Service_Group_ID:Special_Group_ID )){
					mOtherArray.add(jsonObject);
				}
				mChoosedArray.add(jsonObject);
			}
			mAdapter.notifyDataSetChanged();
		}
	}
	

	
	private static class ViewHolder{
		ImageView headerImageV;
		TextView nameTextV;
		ImageView sexImageV;
		ImageView roleImageV;
		TextView noteTextV;
		CheckBox chooseBox;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
			mAdapter.isChoose(position);
	}
}
